


// 配置 Axios 
import axios from "axios"
import { message } from "antd"
import { HashHistroy } from "../utils";

const baseURL = 'http://localhost:3000/'
// const baseURL = 'http://182.92.207.63:3000'; 

axios.defaults.baseURL = baseURL;   // 应用的基路径    设置代理就不要设置基路径
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; // token 
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';  // content-type 文档类型

// import router from "@/router"
var load = null


export function showLoading(msg) {
  msg = msg || '加载中...'
  load && message.destroy()  // 关闭其他的所有Toast 提示
  load = message.loading(msg)

}

export function ShowSuccess(msg) {
  msg = msg || '成功'
  message.destroy();
  message.success(msg)

}

export function ShowFailed(msg) {
  msg = msg || '请求失败'
  message.destroy()
  message.error(msg)
}

// Interceptors 拦截器 
// Add a request interceptor  请求拦截器 
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  console.log(config)   // 请求的参数配置 
  var token = sessionStorage.getItem("token")
  if (token) {
    config['headers'].token = token    // 请求头携带了 token 信息  发送给服务器 
  }
  showLoading()
  return config;
}, function (error) {
  // Do something with request error
  ShowFailed('请求失败')
  return Promise.reject(error);
});

// Add a response interceptor   响应拦截器
axios.interceptors.response.use(function (response) {
  // 根据状态码来判断 结果
  console.log(response.data)
  if (response.data.code == 200) {
    ShowSuccess(response.data.msg)
  } else {
    if (response.data.code == 3000) {   // 重新登录 token 异常 
      // router.push({name:"login"})
      HashHistroy.push("/login")
    }
    ShowFailed(response.data.msg)
  }

  return response;
}, function (error) {
  // 错误的状态码  做些响应的处理 
  ShowFailed('响应失败-服务器异常')
  return Promise.reject(error);
});

export const get = function (url, params, headers) {    // 请求头  params 查询参数 
  return new Promise(function (resolve, reject) {
    axios.get(url, {
      params: params,
      headers: headers
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export const post = function (url, body, headers) {   // headers 请求头  body post请求提交的参数 
  return new Promise(function (resolve, reject) {
    axios.post(url, body, {
      headers
    }).then(res => {
      resolve(res.data)   // 因为 axios 把数据套在 data 里面
    }).catch(err => {
      reject(err)
    })
  })
}

// patch  
// delete 

export {
  axios,
  baseURL
}